<?php
namespace Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Container;
use Intervention\Image\ImageManagerStatic as Image;


class FileApi extends Base
{

    public function __construct(Container $container)
    {
        parent::__construct($container);
        if ($this->getaccount() === false) {
            header("HTTP/1.1 400 Bad Request");
            echo 'no account error';
            exit;
        } else {
            $this->account = $this->getaccount();
        }
    }


    public function uploadfile(Request $req, Response $res)
    {
        $UploadedFiles = $req->getUploadedFiles();
        $file = $UploadedFiles['filedata'];
        $Size = $file->getSize();
        $name = explode('.', $file->getClientFilename());
        $checksize = $this->checksize($Size, 10);
        if ($checksize === false) {
            return $res->withStatus(400)->write('文件过大');
            exit;
        }

        $filetype = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'image/jpeg', 'image/png'];
        if (in_array($name[1], $filetype) === false) {
            return $res->withStatus(400)->write('文件类型错误');
            exit;
        }
        $filepath = $this->checkuploadfile();
        $newname = uniqid() . '.' . $name[1];
        $movefile = $filepath['filepath'] . '/' . $newname;
        $movethumbfile = $filepath['thumbfilepath'] . '/' . $newname;
        Image::make($file->file)->resize(100, 100)->save($movethumbfile);
        $file->moveTo($movefile);
        $data = [
            'errno' => 0,
            'data' => ['/upload/'.$newname]
        ];

        return $res->withJson($data, 200);
        exit;

    }

}